<template>
    <el-form :model="form" label-width="120px" :rules="rules" ref="formRef" class="add-article-form">
        <el-form-item label="标题">
            <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="简介">
            <el-input v-model="form.description" placeholder="请输入简介" />
        </el-form-item>
        <el-form-item label="封面图" prop="cover">
            <el-upload
                :action="action"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="coverRemove"
                name="file"
                :headers="{ 'Authorization': token }"
                :on-success="handleSuccess"
                :before-upload="beforeAvatarUpload"
                accept=".jpg,.jpeg,.png,.gif"
                :show-file-list="false"
                :on-exceed="handleExceed"
            >
                <div v-if="form.cover">
                    <img :src="form.cover" alt="封面图" style="max-height: 146px;max-width: 146px;" />
                </div>
                <div v-else>
                    <el-icon><Plus /></el-icon>
                </div>
            </el-upload>
        </el-form-item>

        <el-form-item>
            <Editor :formData="form" @content="content"  label="内容" prop="content" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
                <el-radio :value="1">启用</el-radio>
                <el-radio :value="0">禁用</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item class="sub-btn">
            <el-button type="primary" @click="submitForm">确定</el-button>
        </el-form-item>
        
    </el-form>
</template>

<script setup>
import { reactive, ref, toRefs, watch } from 'vue';
import { ElMessage } from 'element-plus';
import Editor from '@/components/Editor.vue';
import { Plus } from '@element-plus/icons-vue';
import { sysIntroService } from '@/api/sysIntroService';

const token = localStorage.getItem('token');
const action = '/adminApi/upload';

const formRef = ref(null); // 定义 formRef 引用

// 定义组件接收的属性
const props = defineProps({
    form: {
        type: Object, // 表单数据对象
        required: true // 确保父组件必须传递 form
    },
    mark: {
        type: String, // 组件标识
        default: '' // 默认值为空字符串
    }
});

// 将 `form` 转换为响应式引用
const form = reactive({
    ...props.form // 合并父组件传递的表单数据
});

// 监听 props 的变化并更新 form 数据
watch(
    () => props.form,
    (newForm) => {
        Object.assign(form, newForm || {}); // 更新 form 的值，确保 newForm 存在
    },
    { deep: true, immediate: true } // 深度监听并立即执行
);

//const { title, description, content: formContent, status } = toRefs(form);

// 验证规则
const rules = {
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 2, max: 20, message: '标题长度在2到20个字符之间', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '请输入简介', trigger: 'blur' },
        { min: 2, max: 50, message: '简介长度在2到50个字符之间', trigger: 'blur' }
    ],
    status: [
        { required: true, message: '请选择状态', trigger: 'change' }
    ]
};

const validateForm = async () => {
    try {
        if (!formRef.value) {
            throw new Error('表单实例未定义');
        }
        await formRef.value.validate(); // 使用 formRef 调用 validate 方法
        return true;
    } catch (error) {
        ElMessage.error('请检查表单填写是否正确: ' + error.message);
        return false;
    }
};

const submitForm = async () => {
    // 先验证表单
    const isValid = await validateForm();
    if (!isValid) {
        return;
    }
    if (!form.mark) {
        form.mark = props.mark; // 确保 form 对象中包含 mark 属性
    }
    // 提交表单数据
    sysIntroService.postSysIntro(form).then(res => {
        if (res.code === 1) {
            ElMessage.success('保存成功');
        } else {
            ElMessage.error('保存失败');
        }
    }).catch(error => {
        ElMessage.error('提交失败: ' + error.message);
    });
};

const beforeAvatarUpload = (file) => {
    const isImage = file.type.startsWith('image/'); // 检查 MIME 类型是否以 "image/" 开头
    if (!isImage) {
        ElMessage.error('只能上传图片!');
        return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2; // 限制图片大小为 2MB
    if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!');
        return false;
    }
    return true;
};

const handleSuccess = (response) => {
    if (response.code === 1) {
        form.cover = response.data; // 假设返回的数据中有文件的URL
        ElMessage.success('上传成功');
    } else {
        ElMessage.error('上传失败');
    }
};

const coverRemove = () => {
    form.cover = '';
};

// 内容发生变化时触发 子组件调用
const content = (e) => {
    if (typeof e !== 'string') {
        console.error('内容必须是字符串');
        return;
    }
    console.log('form.content', e);
    form.content = e; // 直接赋值字符串内容
};
</script>

<style scoped>
.sub-btn {
    text-align: center;
    margin-top: 80px;
}
  
</style>